package com.ruoyi.statistics.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.domain.TreeEntity;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.statistics.domain.HomeStatistics;
import com.ruoyi.statistics.mapper.HomeMapper;
import com.ruoyi.statistics.service.HomeService;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.service.ISysConfigService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
public class HomeServiceImpl implements HomeService {

    private final HomeMapper homeMapper;

    private final SysDeptMapper sysDeptMapper;

    private final ISysConfigService sysConfigService;


    @Override
    public HomeStatistics homeHead(HomeStatistics homeStatistics) {
        dataPermission(homeStatistics, "headData");
        return homeMapper.homeHead(homeStatistics);
    }

    @Override
    public List<HomeStatistics> teamYjData(HomeStatistics homeStatistics) {
        dataPermission(homeStatistics, "teamYjData");

        List<HomeStatistics> teamStatistics = homeMapper.teamStatistics(homeStatistics);

        if (CollectionUtils.isEmpty(teamStatistics)) {
            return Collections.emptyList();
        }
        List<HomeStatistics> homeStatisticsList = new ArrayList<>();
        if (Objects.equals(homeStatistics.getType(), "1")) {
            // 团队取前五--业务员登录
            return teamStatistics.stream().
                    sorted(Comparator.comparing(HomeStatistics::getTeamRevenue).reversed()).
                    limit(5).collect(Collectors.toList());
        } else {
            // 当前登录人存在下级部门
            if (homeStatistics.isDeptFlag()) {
                List<SysDept> deptList = homeStatistics.getDeptList();
                for (SysDept sysDept : deptList) {
                    HomeStatistics deptStatistics = new HomeStatistics();
                    deptStatistics.setDeptName(sysDept.getDeptName());
                    String ancestors = sysDept.getAncestors() + "," + sysDept.getDeptId();
                    List<BigDecimal> collect = teamStatistics.stream().filter(it -> {
                        return it.getAncestors().contains(ancestors);
                    }).map(HomeStatistics::getTeamRevenue).collect(Collectors.toList());
                    BigDecimal teamRevenue = new BigDecimal("0.00");
                    for (BigDecimal bigDecimal : collect) {
                        teamRevenue = teamRevenue.add(bigDecimal);
                    }
                    deptStatistics.setTeamRevenue(teamRevenue);
                    deptStatistics.setDeptId(sysDept.getDeptId());
                    homeStatisticsList.add(deptStatistics);
                }
                if (!CollectionUtils.isEmpty(homeStatisticsList)) {
                    return homeStatisticsList.stream().
                            filter(it -> it.getTeamRevenue().compareTo(BigDecimal.ZERO) > 0).
                            sorted(Comparator.comparing(HomeStatistics::getTeamRevenue).reversed()).
                            limit(5).collect(Collectors.toList());
                }
            } else {
                // 团队取前五--业务员登录
                return teamStatistics.stream().
                        filter(it -> it.getTeamRevenue().compareTo(BigDecimal.ZERO) > 0).
                        sorted(Comparator.comparing(HomeStatistics::getTeamRevenue).reversed()).
                        limit(5).collect(Collectors.toList());
            }
        }
        return Collections.emptyList();
    }

    @Override
    public List<HomeStatistics> personYjData(HomeStatistics homeStatistics) {
        dataPermission(homeStatistics, "personYjData");
        List<HomeStatistics> homeStatistics1 = homeMapper.userStatistics(homeStatistics);
        if (!CollectionUtils.isEmpty(homeStatistics1)) {
            return homeStatistics1.stream().
                    filter(it -> it.getUserRevenue().compareTo(BigDecimal.ZERO) > 0).
                    sorted(Comparator.comparing(HomeStatistics::getUserRevenue).reversed()).
                    limit(5).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }


    @Override
    public List<HomeStatistics> yearQuota(HomeStatistics homeStatistics) {
        dataPermission(homeStatistics, "yearQuota");
        homeStatistics.setYear(DateUtils.parseDateToStr(DateUtils.YYYY, DateUtils.getNowDate()));
        List<HomeStatistics> homeStatistics1 = homeMapper.yearQuota(homeStatistics);
        if (!CollectionUtils.isEmpty(homeStatistics1)) {
            return homeStatistics1;
        }
        return Collections.emptyList();
    }

    @Override
    public List<HomeStatistics> atDayRecord(HomeStatistics homeStatistics) {
        dataPermission(homeStatistics, "atDayRecord");
        List<HomeStatistics> homeStatisticsList = homeMapper.atDayRecord(homeStatistics);
        if (!CollectionUtils.isEmpty(homeStatisticsList)) {
            homeStatisticsList.forEach(it -> {
                List<String> recordNumbers = homeMapper.recordCustomerNumber(it.getUserId());
                if (!CollectionUtils.isEmpty(recordNumbers)) {
                    it.setCustomerNum(String.valueOf(recordNumbers.size()));
                } else {
                    it.setCustomerNum("0");
                }
            });
            return homeStatisticsList;
        }
        return Collections.emptyList();
    }


    private void dataPermission(HomeStatistics homeStatistics, String type) {
        //String key = sysConfigService.selectConfigByKey(Constants.SALESMAN_ROLEKEY_TYPE);
        //
        //List<Long> sysUsers = homeMapper.dataUser(key);
        //if (CollectionUtils.isEmpty(sysUsers)) {
        //    return;
        //}
        // 如果是业务员登录
        Long userId = LoginHelper.getLoginUser().getUserId();
        Long deptId = LoginHelper.getLoginUser().getDeptId();

        String leader = LoginHelper.getLoginUser().getLeader();
        // 业务员登录
        if (!Objects.equals("1", leader)) {
            homeStatistics.setOperation("1");
            // 头部数据
            if (Objects.equals("headData", type)) {
                homeStatistics.setType("and u.user_id = " + userId);
                homeStatistics.setTypeOther(" and EXISTS (SELECT 1 from t_reviewe_cooperate rc where rc.reviewe_id = a.id AND rc.user_id = " + userId + " ) ");
            }
            // 团队业绩
            if (Objects.equals("teamYjData", type)) {
                homeStatistics.setType("and d.dept_id = " + deptId);
            }
            // 每天备注统计
            if (Objects.equals("atDayRecord", type)) {
                homeStatistics.setType("and d.dept_id = " + deptId);
            }
            // 个人业绩 查看自己部门
            if (Objects.equals("personYjData", type)) {
                homeStatistics.setType("and d.dept_id = " + deptId);
            }
            // 年度信息
            if (Objects.equals("yearQuota", type)) {
                homeStatistics.setType("and a.user_id = " + userId);
            }
        } else {
            homeStatistics.setOperation("2");
            // 头部数据
            if (Objects.equals("headData", type)) {
                homeStatistics.setType(" AND (d.ancestors LIKE  '" + LoginHelper.getLoginUser().getChildren() + "%' OR d.dept_id = " + deptId + " )");
                homeStatistics.setTypeOther(" and EXISTS (SELECT 1 from t_reviewe_cooperate rc left join sys_dept dd on rc.dept_id = dd.dept_id  where rc.reviewe_id = a.id  AND ( dd.ancestors LIKE  '" + LoginHelper.getLoginUser().getChildren() + "%' OR dd.dept_id = " + deptId + " )" + " ) ");
            }
            // 团队业绩
            if (Objects.equals("teamYjData", type)) {
                // 查询当前部门下面的parentId为自己的部门 如果下面存在部门 就取自己下面的  否则就是当前部门
                LambdaQueryWrapper<SysDept> sysDeptLambdaQueryWrapper = new LambdaQueryWrapper<>();
                sysDeptLambdaQueryWrapper.eq(TreeEntity::getParentId, deptId);
                sysDeptLambdaQueryWrapper.orderByDesc(SysDept::getDeptId);
                List<SysDept> sysDepts = sysDeptMapper.selectVoList(sysDeptLambdaQueryWrapper);
                if (CollectionUtils.isEmpty(sysDepts)) {
                    homeStatistics.setType("and d.dept_id = " + deptId);
                } else {
                    homeStatistics.setDeptList(sysDepts);
                    homeStatistics.setDeptFlag(true);
                }
            }
            // 每天备注统计
            if (Objects.equals("atDayRecord", type)) {
                homeStatistics.setType(" and ( d.ancestors like '%" + deptId + "%' or d.dept_id = " + deptId + " )");
            }
            // 个人业绩
            if (Objects.equals("personYjData", type)) {
                homeStatistics.setType("and ( d.ancestors like '" + LoginHelper.getLoginUser().getChildren() + "%'" + " OR d.dept_id = " + deptId + " )");
            }

            // 年度信息
            if (Objects.equals("yearQuota", type)) {
                homeStatistics.setType("and ( d.ancestors like '" + LoginHelper.getLoginUser().getChildren() + "%'" + " OR d.dept_id = " + deptId + " )");
            }



        }



    }
}
